﻿// 
// DotNetNuke® - http://www.dotnetnuke.com
// Copyright (c) 2002-2011
// by DotNetNuke Corporation
// 
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated 
// documentation files (the "Software"), to deal in the Software without restriction, including without limitation 
// the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and 
// to permit persons to whom the Software is furnished to do so, subject to the following conditions:
// 
// The above copyright notice and this permission notice shall be included in all copies or substantial portions 
// of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 
// TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
// CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
// DEALINGS IN THE SOFTWARE.


using System;

using DotNetNuke;
using DotNetNuke.Common;
using DotNetNuke.Common.Utilities;
using DotNetNuke.Entities.Modules;
using DotNetNuke.Services.Exceptions;
using DotNetNuke.Services.Localization;
using System.Globalization;
using System.Web.UI.WebControls;
using System.Collections.Generic;
using System.Text;
using System;
using System.IO;
using Triax.Modules.ThongKeATLD;

using ServiceReference1;
using System.Data;

namespace Triax.Modules.CSDLAnhHien
{
    /// -----------------------------------------------------------------------------
    /// <summary>
    /// The EditCSDLAnhHien class is used to manage content
    /// </summary>
    /// <remarks>
    /// </remarks>
    /// <history>
    /// </history>
    /// -----------------------------------------------------------------------------
    partial class EditCSDLAnhHien : PortalModuleBase
    {

        #region Private Members

        private int ItemId = Null.NullInteger;
        int level = -1;
        #endregion

        #region Event Handlers

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// Page_Load runs when the control is loaded
        /// </summary>
        /// <remarks>
        /// </remarks>
        /// <history>
        /// </history>
        /// -----------------------------------------------------------------------------
        protected void Page_Load(System.Object sender, System.EventArgs e)
        {
            try
            {

                // this.Control.Visible = false;

                //If this is the first visit to the page, bind the role data to the datalist
                if (Page.IsPostBack == false)
                {
                    BindThang();
                    ShowValue();
                 BindKyBaoCao();
                 BindCSDL();
                 BindNhom();
                 txtThoigian1.Text = new DateTime(DateTime.Now.Year, 1, 1).ToString("dd/MM/yyyy");
                 txtThoigian2.Text = new DateTime(DateTime.Now.Year, 12, 31, 23, 59, 59).ToString("dd/MM/yyyy");
                    this.EnableViewState = true;

                }
            }
            catch (Exception exc) //Module failed to load
            {
                Exceptions.ProcessModuleLoadException(this, exc);
            }
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// cmdCancel_Click runs when the cancel button is clicked
        /// </summary>
        /// <remarks>
        /// </remarks>
        /// <history>
        /// </history>
        /// -----------------------------------------------------------------------------
        protected void cmdCancel_Click(System.Object sender, System.EventArgs e)
        {
            try
            {
                this.Response.Redirect(Globals.NavigateURL(this.TabId), true);
            }
            catch (Exception exc) //Module failed to load
            {
                Exceptions.ProcessModuleLoadException(this, exc);
            }
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// cmdDelete_Click runs when the delete button is clicked
        /// </summary>
        /// <remarks>
        /// </remarks>
        /// <history>
        /// </history>
        /// -----------------------------------------------------------------------------
       

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// cmdUpdate_Click runs when the update button is clicked
        /// </summary>
        /// <remarks>
        /// </remarks>
        /// <history>
        /// </history>
        /// -----------------------------------------------------------------------------
        protected void cmdUpdate_Click(System.Object sender, System.EventArgs e)
        {
            ServiceReference1.BIPortalClient client = new ServiceReference1.BIPortalClient();

          //  ServiceReference1.BIPortalClient client = new BIPortalClient();

            string _DBName = drChonCSDL.SelectedValue;
            DateTime tungay = DateTime.Now;
            DateTime denngay = DateTime.Now;
            List<Triax.Modules.ThongKeATLD.DonViHanhChinhInfo> listobject = new List<Triax.Modules.ThongKeATLD.DonViHanhChinhInfo>();
            try
            {
                tungay = DateTime.Parse(convertdate(txtThoigian1.Text));
            }
            catch
            {
                tungay = DateTime.Now.AddDays(-1);
            }
            try
            {
                denngay = DateTime.Parse(convertdate(txtThoigian2.Text));
                denngay = new DateTime(denngay.Year, denngay.Month, denngay.Day, 23, 59, 59);
            }
            catch
            {
                denngay = DateTime.Now;
            }
        
            // Cái cuối cùng là Nhật ký thu chi
            string vl = "";
            string str2 = "";
            string theader = "";
            str2 += "<table cellpadding=\"0\" cellspacing=\"0\" border=\"0\" class=\"display\" id=\"example\">";
            str2 += "	<thead>";
            str2 += "		<tr>";
            str2 += "			<th>Mã đối tượng</th>";
            str2 += "			<th>Tên đối tượng</th>";
            str2 += "			<th>Ngày ghi số</th>";
            str2 += "			<th>Số</th>";
            str2 += "			<th>Ngày</th>";
            str2 += "			<th>Diễn giải</th>";
            str2 += "			<th>Tài khoản nợ</th>";
            str2 += "			<th>tài khoản có</th>";
            str2 += "			<th>Giá trị</th>";
            str2 += "		</tr>";
            str2 += "	</thead>";
            str2 += "	<tfoot>";
            str2 += "		<tr>";
            str2 += "";
            str2 += "			<th>Mã đối tượng</th>";
            str2 += "			<th>Tên đối tượng</th>";
            str2 += "			<th>Ngày ghi số</th>";
            str2 += "			<th>Số</th>";
            str2 += "			<th>Ngày</th>";
            str2 += "			<th>Diễn giải</th>";
            str2 += "			<th>Tài khoản nợ</th>";
            str2 += "			<th>tài khoản có</th>";
            str2 += "			<th>Giá trị</th>";
            str2 += "		</tr>";
            str2 += "	</tfoot>";
            str2 += "	<tbody>";
            string strOp1 = "";
            strOp1 += "<table cellpadding=\"0\" cellspacing=\"0\" border=\"0\" class=\"display\" id=\"example\">";
            strOp1 += "	<thead>";
            strOp1 += "		<tr>";

            strOp1 += "			<th>Tên đối tượng</th>";
            strOp1 += "			<th>Ngày ghi số</th>";
            strOp1 += "			<th>Số</th>";
            strOp1 += "			<th>Ngày</th>";
            strOp1 += "			<th>Diễn giải</th>";
            strOp1 += "			<th>Tài khoản nợ</th>";
            strOp1 += "			<th>tài khoản có</th>";
            strOp1 += "			<th>Giá trị</th>";
            strOp1 += "		</tr>";
            strOp1 += "	</thead>";
            strOp1 += "	<tfoot>";
            strOp1 += "		<tr>";
            strOp1 += "";

            strOp1 += "			<th>Tên đối tượng</th>";
            strOp1 += "			<th>Ngày ghi số</th>";
            strOp1 += "			<th>Số</th>";
            strOp1 += "			<th>Ngày</th>";
            strOp1 += "			<th>Diễn giải</th>";
            strOp1 += "			<th>Tài khoản nợ</th>";
            strOp1 += "			<th>tài khoản có</th>";
            strOp1 += "			<th>Giá trị</th>";
            strOp1 += "		</tr>";
            strOp1 += "	</tfoot>";
            strOp1 += "	<tbody>";
            string strOp2 = "";
            strOp2 += "<table cellpadding=\"0\" cellspacing=\"0\" border=\"0\" class=\"display\" id=\"example\">";
            strOp2 += "	<thead>";
            strOp2 += "		<tr>";
            strOp2 += "			<th>Tài khoản nợ</th>";
            strOp2 += "			<th>Tên đối tượng</th>";
            strOp2 += "			<th>Ngày ghi số</th>";
            strOp2 += "			<th>Số</th>";
            strOp2 += "			<th>Ngày</th>";
            strOp2 += "			<th>Diễn giải</th>";

            strOp2 += "			<th>tài khoản có</th>";
            strOp2 += "			<th>Giá trị</th>";
            strOp2 += "		</tr>";
            strOp2 += "	</thead>";
            strOp2 += "	<tfoot>";
            strOp2 += "		<tr>";
            strOp2 += "";
            strOp2 += "			<th>Tài khoản nợ</th>";
            strOp2 += "			<th>Tên đối tượng</th>";
            strOp2 += "			<th>Ngày ghi số</th>";
            strOp2 += "			<th>Số</th>";
            strOp2 += "			<th>Ngày</th>";
            strOp2 += "			<th>Diễn giải</th>";

            strOp2 += "			<th>tài khoản có</th>";
            strOp2 += "			<th>Giá trị</th>";
            strOp2 += "		</tr>";
            strOp2 += "	</tfoot>";
            strOp2 += "	<tbody>";
            string strOp3 = "";
            strOp3 += "<table cellpadding=\"0\" cellspacing=\"0\" border=\"0\" class=\"display\" id=\"example\">";
            strOp3 += "	<thead>";
            strOp3 += "		<tr>";
            strOp3 += "			<th>Tài khoản có</th>";
            strOp3 += "			<th>Tên đối tượng</th>";
            strOp3 += "			<th>Ngày ghi số</th>";
            strOp3 += "			<th>Số</th>";
            strOp3 += "			<th>Ngày</th>";
            strOp3 += "			<th>Diễn giải</th>";
            strOp3 += "			<th>Tài khoản nợ</th>";

            strOp3 += "			<th>Giá trị</th>";
            strOp3 += "		</tr>";
            strOp3 += "	</thead>";
            strOp3 += "	<tfoot>";
            strOp3 += "		<tr>";
            strOp3 += "";
            strOp3 += "			<th>Tài khoản có</th>";
            strOp3 += "			<th>Tên đối tượng</th>";
            strOp3 += "			<th>Ngày ghi số</th>";
            strOp3 += "			<th>Số</th>";
            strOp3 += "			<th>Ngày</th>";
            strOp3 += "			<th>Diễn giải</th>";
            strOp3 += "			<th>Tài khoản nợ</th>";

            strOp3 += "			<th>Giá trị</th>";
            strOp3 += "		</tr>";
            strOp3 += "	</tfoot>";
            strOp3 += "	<tbody>";
            int count = 0;
            try
            {
                client.ClientCredentials.Windows.ClientCredential.UserName = "other";
                client.ClientCredentials.Windows.ClientCredential.Password = "123";
                DateTime now = DateTime.Now;
                string xml = client.NhatKyThuOrChiOut(_DBName, tungay, denngay, true);


                Stream stream = StringToStream(xml);
                DataSet ds = new DataSet();
                ds.ReadXml(stream);
                DataTable dt = ds.Tables[0]; ;
             
                //Phải đọc qua dataset, qua table trực tiếp k được
              
               //  ds.ReadXml(stream);
               //DataTable dt = ds.Tables[0];
                string cssclass = "even_gradeC";
                foreach (DataRow row in dt.Rows)
                {
                    count++;
                    
                    if(count %2==0)
                    {
                        cssclass = "odd_gradeA";
                    }else
                    {
                        cssclass = "even_gradeC";
                    }
                    string key = "";
                    string values = "";
                    decimal value = (decimal)0;
                    string   MaDoiTuong = "";
string   TenDoiTuong = "";
string   NgayGhiSo = "";
string   So = "";
string   Ngay = "";
string   DienGiai = "";
string   SoHieuTaiKhoanNo = "";
string   SoHieuTaiKhoanCo = "";
string GiaTri = "";

                    // Row: Name, Month,Year,Amount
                    if (row != null)
                    {
                        
                        if (row["MaDoiTuong"] is string)
                            MaDoiTuong = row["MaDoiTuong"].ToString();

                        if (row["TenDoiTuong"] is string)
                            TenDoiTuong = row["TenDoiTuong"].ToString();

                        if (row["NgayGhiSo"] is string)
                            NgayGhiSo = row["NgayGhiSo"].ToString();
                        So = row["So"].ToString();
                        Ngay = row["Ngay"].ToString();
                        DienGiai = row["DienGiai"].ToString();
                        SoHieuTaiKhoanNo = row["SoHieuTaiKhoanNo"].ToString();
                        SoHieuTaiKhoanCo = row["SoHieuTaiKhoanCo"].ToString();
                        GiaTri = row["GiaTri"].ToString();
                        vl += "MaDoiTuong: " + MaDoiTuong + " TenDoiTuong: " + TenDoiTuong + " So " + So + " Ngay " + Ngay + " DienGiai: " + DienGiai + " SoHieuTaiKhoanNo: " + SoHieuTaiKhoanNo + " SoHieuTaiKhoanCo : " + SoHieuTaiKhoanCo + " GiaTri : " + GiaTri + "<br/>";
                        /*
                        str2 += "<tr class=\"" + cssclass + "\" id=\"" + count + "\">";
                        str2 += "<td>" + MaDoiTuong + "</td>";
                        str2 += "<td>" + TenDoiTuong + "</td>";
                        str2 += "<td>" + convertTime(NgayGhiSo) + "</td>";
                        str2 += "<td>" + So + "</td>";
                        str2 += "<td>" + convertTime(Ngay) + "</td>";
                        str2 += "<td>" + DienGiai + "</td>";
                        str2 += "<td>" + SoHieuTaiKhoanNo + "</td>";
                        str2 += "<td>" + SoHieuTaiKhoanCo + "</td>";
                        str2 += "<td style=\"width:100px\"> <font color=\"red\">" + String.Format("{0:### ### ### ###}", Decimal.Parse(GiaTri)) + "</font></td>";
                        str2 += "</tr>";
                         * */
                        // gan vao doi duong
                        Triax.Modules.ThongKeATLD.DonViHanhChinhInfo objTD = new ThongKeATLD.DonViHanhChinhInfo();
                        objTD.code = MaDoiTuong;
                        objTD.title = TenDoiTuong;
                        objTD.Description = NgayGhiSo + ";" + Ngay + ";" + So + ";" + GiaTri;
                        objTD.temp_string1 = DienGiai;
                        objTD.temp_string2 = SoHieuTaiKhoanNo;
                        objTD.temp_string3 = SoHieuTaiKhoanCo;
                        objTD.temp_double1  =Double.Parse(GiaTri);
                        listobject.Add(objTD);
                    }
                }
                List<DonViHanhChinhInfo> kiemtra = new List<DonViHanhChinhInfo>();
                // tính tổng giá trị
                for (int i = 0; i < listobject.Count;i++ )
                {
                    kiemtra = Addgiatri(kiemtra, listobject[i],int.Parse(drNhomDoiTuong.SelectedValue));
                }
                int option = int.Parse(drNhomDoiTuong.SelectedValue);
                if (option == 1)
                {
                    //for (int i = 0; i < listobject.Count; i++)
                    //{
                    //    for (int j = 0; j < kiemtra.Count; j++)
                    //    {
                    //        if (listobject[i].title.CompareTo(kiemtra[j].title) == 0)
                    //        {
                    //            listobject[i].title += " (Số phát sinh = " + kiemtra[j].temp_double1 + ")";
                    //        }
                    //    }
                    //}
                }
                if (option == 2)
                {
                    //for (int i = 0; i < listobject.Count; i++)
                    //{
                    //    for (int j = 0; j < kiemtra.Count; j++)
                    //    {
                    //        if (listobject[i].temp_string2.CompareTo(kiemtra[j].temp_string2) == 0)
                    //        {
                    //            listobject[i].temp_string2 += " (Số phát sinh = " + kiemtra[j].temp_double1 + ")";
                    //        }
                    //    }
                    //}
                }
                if (option == 3)
                {
                    //for (int i = 0; i < listobject.Count; i++)
                    //{
                    //    for (int j = 0; j < kiemtra.Count; j++)
                    //    {
                    //        if (listobject[i].temp_string3.CompareTo(kiemtra[j].temp_string3) == 0)
                    //        {
                    //            listobject[i].temp_string3 += " (Số phát sinh = " + kiemtra[j].temp_double1 + ")";
                    //        }
                    //    }
                    //}
                }


                if (option == 1)
                {
                    for (int i = 0; i < listobject.Count; i++)
                    {
                        strOp1 += "<tr class=\"" + cssclass + "\" id=\"" + count + "\">";
                        strOp1 += "<td>" + getCode(kiemtra, listobject[i],1) + "</td>";
                        
                        string[] ngaygs = listobject[i].Description.Split(';');
                        strOp1 += "<td>" + convertTime(ngaygs[0]) + "</td>";
                        strOp1 += "<td>" + (ngaygs[2]) + "</td>";
                        strOp1 += "<td>" + convertTime(ngaygs[1]) + "</td>";
                        strOp1 += "<td>" + listobject[i].temp_string1 + "</td>";
                        strOp1 += "<td>" + listobject[i].temp_string2 + "</td>";
                        strOp1 += "<td>" + listobject[i].temp_string3 + "</td>";
                        if (Double.Parse(ngaygs[3]) > 0)
                        {
                            strOp1 += "<td style=\"width:100px\"> <font color=\"red\">" + String.Format("{0:### ### ### ###}", Double.Parse(ngaygs[3])) + "</font></td>";
                        }
                        else
                        {
                            strOp1 += "<td style=\"width:100px\"> <font color=\"red\"> 0" + "</font></td>";

                        }

                        strOp1 += "</tr>";
                    }

                    strOp1 += "</tbody>";
                    strOp1 += "</table>";
                    thongbao.Text = Server.HtmlDecode(strOp1);
                }
                if (option == 2)
                {
                    for (int i = 0; i < listobject.Count; i++)
                    {
                        string[] ngaygs = listobject[i].Description.Split(';');
                        strOp2 += "<tr class=\"" + cssclass + "\" id=\"" + count + "\">";

                        strOp2 += "<td>" + getCode(kiemtra, listobject[i], 2) + "</td>";
                        strOp2 += "<td>" + listobject[i].title + "</td>"; // ten doi duong
                        strOp2 += "<td>" + convertTime(ngaygs[0]) + "</td>"; //ngaygs ghi
                        strOp2 += "<td>" + (ngaygs[2]) + "</td>"; // số
                        
                        
                        strOp2 += "<td>" + convertTime(ngaygs[1]) + "</td>";
                        strOp2 += "<td>" + listobject[i].temp_string1 + "</td>";

                        strOp2 += "<td>" + listobject[i].temp_string3 + "</td>";
                        if (Double.Parse(ngaygs[3]) > 0)
                        {
                            strOp2 += "<td style=\"width:100px\"> <font color=\"red\">" + String.Format("{0:### ### ### ###}", Double.Parse(ngaygs[3])) + "</font></td>";
                        }
                        else
                        {
                            strOp2 += "<td style=\"width:100px\"> <font color=\"red\"> 0" + "</font></td>";

                        }

                        strOp2 += "</tr>";
                    }

                    strOp2 += "</tbody>";
                    strOp2 += "</table>";
                    thongbao.Text = Server.HtmlDecode(strOp2);
                }
                if (option == 3)
                {
                    for (int i = 0; i < listobject.Count; i++)
                    {
                        strOp3 += "<tr class=\"" + cssclass + "\" id=\"" + count + "\">";


                        strOp3 += "<td>" + getCode(kiemtra, listobject[i], 3) + "</td>";
                        string[] ngaygs = listobject[i].Description.Split(';');
                        strOp3 += "<td>" + listobject[i].title + "</td>"; // ten doi duong
                        strOp3 += "<td>" + convertTime(ngaygs[0]) + "</td>"; //ngaygs ghi
                        strOp3 += "<td>" + (ngaygs[2]) + "</td>"; // số


                        strOp3 += "<td>" + convertTime(ngaygs[1]) + "</td>";
                        strOp3 += "<td>" + listobject[i].temp_string1 + "</td>";

                        strOp3 += "<td>" + listobject[i].temp_string2 + "</td>";
                        if (Double.Parse(ngaygs[3]) > 0)
                        {
                            strOp3 += "<td style=\"width:100px\"> <font color=\"red\">" + String.Format("{0:### ### ### ###}", Double.Parse(ngaygs[3])) + "</font></td>";
                        }
                        else
                        {
                            strOp3 += "<td style=\"width:100px\"> <font color=\"red\"> 0" + "</font></td>";

                        }

                        strOp3 += "</tr>";
                    }

                    strOp3 += "</tbody>";
                    strOp3 += "</table>";
                    thongbao.Text = Server.HtmlDecode(strOp3);
                }
                //Phải đọc qua dataset, qua table trực tiếp k được
            }
            catch (Exception exx)
            {
                thongbao.Text = Server.HtmlDecode("Lỗi kết nối đến CSDL");
                //thongbao.Text = exx.ToString();
            }


    }
        public static Stream StringToStream(string str)
        {
            MemoryStream stream = new MemoryStream();
            StreamWriter writer = new StreamWriter(stream);
            writer.Write(str);
            writer.Flush();
            stream.Position = 0;
            return stream;
        }
        public string showvalue(string v)
        {
            string res = "";
            if (v == "-1")
                return "";

            res = Convert.ToSingle(v).ToString();
            return res;

        }
        public bool validate()
        {
            bool res = true;
            string mess = "";
            string startDate = txtThoigian1.Text;
            string endDate = txtThoigian2.Text;
            if (startDate != "")
            {
                try
                {
                    DateTime d1 = DateTime.Parse(startDate);
                }
                catch
                {
                    res = false;
                    mess +=" Lỗi Ngày tháng (Từ ngày)";
                }
            }
            if (endDate != "")
            {
                try
                {
                    DateTime d1 = DateTime.Parse(endDate);
                }
                catch
                {
                    res = false;
                    mess += " Lỗi Ngày tháng (đến ngày)";
                }
            }

            Error.Text = mess;
            

            return res;
        }

        public string getTitle()
        {
            string res = "";
            
            string startDate = txtThoigian1.Text;
            string endDate = txtThoigian2.Text;

            if (startDate.Length > 0)
            {
                if (endDate.Length == 0)
                {
                    res = "TỔNG HỢP VỤ VIỆC NGÀY: " + startDate + "";
                }
                else
                {
                    if ((startDate.Length > 0) && (endDate.Length > 0))
                    {
                        res = " TỔNG HỢP VỤ VIỆC TỪ NGÀY " + startDate + " ĐẾN NGÀY " + endDate + "";
                    }

                }
            }
            return res;
        }
        public string getCond()
        {
            string cond = "";
            return cond;
        }

        public string getCondcongty()
        {
            string cond = "";
       
            return cond;
        }
            
        protected void getTinhThanh()
        {

            //   RecursiveFillTree2(p, 0);

        }

       



        #endregion

       

       
     

        protected void BindThang()
        {
            drThang.Items.Clear();

            for (int i = 5; i < 10; i++)
            {
                drThang.Items.Add(new ListItem(i.ToString(),i.ToString()));
            }
            
            //   drLoaibaocao.SelectedValue = ModuleDepartmentConst._ON.ToString();
            drThang.DataBind();
        }
        protected void BindNhom()
        {
            drNhomDoiTuong.Items.Clear();


            drNhomDoiTuong.Items.Add(new ListItem("Nhóm theo đối tượng", "1"));
            drNhomDoiTuong.Items.Add(new ListItem("Nhóm theo tài khoản nợ", "2"));
            drNhomDoiTuong.Items.Add(new ListItem("Nhóm theo tài khoản có", "3"));
           

            //   drLoaibaocao.SelectedValue = ModuleDepartmentConst._ON.ToString();
            drNhomDoiTuong.DataBind();
        }


        protected void BindCSDL()
        {
            string[] datas = new string[] {"ThanhVinh2Center","ThanhVinh1Center","BachKhoaCenter","HuyHoangCenter","HuyHoangSGCenter"};
            string[] datas2 = new string[] { "Thành vinh 2", "Thành vinh 1", "Bách khoa", "Ngọc hà", "Sài gòn" };
            drChonCSDL.Items.Clear();

            for (int i = 0; i < Triax.Modules.Department.ModuleDepartmentConst.datasTitie.Length; i++)
            {
                drChonCSDL.Items.Add(new ListItem(Triax.Modules.Department.ModuleDepartmentConst.datasTitie[i], Triax.Modules.Department.ModuleDepartmentConst.datas[i]));
            }
          

            //   drLoaibaocao.SelectedValue = ModuleDepartmentConst._ON.ToString();
            drChonCSDL.DataBind();
        }


          protected void BindKyBaoCao()
        {
            drKyBaoCao.Items.Clear();
              string [] datas = new string[] {"Cả năm","Quý I","Quý II","Quý III","Quý IV","Tháng 1","Tháng 2","Tháng 3","Tháng 4","Tháng 5","Tháng 6","Tháng 7","Tháng 8","Tháng 9","Tháng 10","Tháng 11","Tháng 12","Tuần gần nhất","Tháng này","Hôm qua","Hôm nay","Tùy chọn"};

            for (int i = 0; i < datas.Length; i++)
            {
                drKyBaoCao.Items.Add(new ListItem(datas[i],datas[i]));
            }
            
            //   drLoaibaocao.SelectedValue = ModuleDepartmentConst._ON.ToString();
            drKyBaoCao.DataBind();
        }

        protected void ShowValue()
        {
            drShow.Items.Clear();


            drShow.Items.Add(new ListItem("--------", "0"));
                drShow.Items.Add(new ListItem("Hiện", "1"));
                drShow.Items.Add(new ListItem("Ẩn", "2"));
          

            //   drLoaibaocao.SelectedValue = ModuleDepartmentConst._ON.ToString();
            drShow.DataBind();
        }

        
        // đổi ra số la mã
        public string ToRoman(int number)
        {
            if (-9999 >= number || number >= 9999)
            {
                return "";
            }

            if (number == 0)
            {
                return "";
            }

            StringBuilder sb = new StringBuilder(10);

            if (number < 0)
            {
                sb.Append('-');
                number *= -1;
            }

            string[,] table = new string[,] { 
        { "", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX" }, 
        { "", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC" }, 
        { "", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM" },
        { "", "M", "MM", "MMM", "M(V)", "(V)", "(V)M", 
                                          "(V)MM", "(V)MMM", "M(X)" } 
    };

            for (int i = 1000, j = 3; i > 0; i /= 10, j--)
            {
                int digit = number / i;
                sb.Append(table[j, digit]);
                number -= digit * i;
            }

            return sb.ToString();
        }
       
       
         private class ChartData
         {
             public String Mounth { get; set; }
             public Double Money { get; set; }
             public String Key { get; set; }
             public int Values { get; set; }

             public static List<ChartData> CreateCompanyList1()
             {
                 List<ChartData> company1 = new List<ChartData>();
                 company1.Add(new ChartData() { Mounth = "January", Money = 100 });
                 company1.Add(new ChartData() { Mounth = "February", Money = 120 });
                 company1.Add(new ChartData() { Mounth = "March", Money = 140 });
                 return company1;
             }

             public static List<ChartData> CreateCompanyList2() 
             {
                 List<ChartData> company2 = new List<ChartData>();
                 company2.Add(new ChartData() { Mounth = "January", Money = 80 });
                 company2.Add(new ChartData() { Mounth = "February", Money = 160 });
                 company2.Add(new ChartData() { Mounth = "March", Money = 130 });
                 return company2;
             }
         }
         protected void drNhomDoiTuong_SelectedIndexChanged(object sender, System.EventArgs e)
         {
             ServiceReference1.BIPortalClient client = new ServiceReference1.BIPortalClient();
         }
         protected void drKyBaoCao_SelectedIndexChanged(object sender, System.EventArgs e)
         {
             ServiceReference1.BIPortalClient client = new ServiceReference1.BIPortalClient();

             DateTime ngayBatDau = DateTime.Now;
             //DateTime.Parse(txtThoigian1.Text);
             DateTime ngayKetThuc = DateTime.Now; //DateTime.Parse(txtThoigian2.Text);
             DateTime now = DateTime.Now;
             switch (drKyBaoCao.SelectedItem.Text)
             {
                 case "Hôm nay":
                     txtThoigian1.Enabled = true;
                     txtThoigian1.Enabled = true;
                     ngayBatDau = new DateTime(now.Year, now.Month, now.Day, 0, 0, 0);
                     ngayKetThuc = new DateTime(now.Year, now.Month, now.Day, 23, 59, 59);
                     break;
                 case "Hôm qua":
                     txtThoigian1.Enabled = false;
                     txtThoigian2.Enabled = false;
                     ngayBatDau = new DateTime(now.Year, now.Month, now.Day, 0, 0, 0).AddDays(-1);
                     ngayKetThuc = new DateTime(now.Year, now.Month, now.Day, 23, 59, 59).AddDays(-1);
                     break;
                 case "Tuần gần nhất":
                     txtThoigian1.Enabled = false;
                     txtThoigian2.Enabled = false;
                     ngayBatDau = new DateTime(now.Year, now.Month, now.Day, 0, 0, 0).AddDays(-7);
                     ngayKetThuc = new DateTime(now.Year, now.Month, now.Day, 23, 59, 59);
                     break;
                 case "Tháng này":
                     txtThoigian1.Enabled = false;
                     txtThoigian2.Enabled = false;
                     ngayBatDau = new DateTime(now.Year, now.Month, 1, 0, 0, 0);
                     ngayKetThuc = new DateTime(now.Year, now.Month, System.DateTime.DaysInMonth(now.Year, now.Month), 23, 59, 59);
                     break;
                 case "Tùy chọn":
                     txtThoigian1.Enabled = true;
                     txtThoigian2.Enabled = true;
                     try
                     {
                         if (drChonCSDL.Text == "")
                         {
                             Error.Text = "Cần chọn Chi nhánh - CSDL";
                             drChonCSDL.Focus();
                             return;
                         }
                         client.ClientCredentials.Windows.ClientCredential.UserName = "other";
                         client.ClientCredentials.Windows.ClientCredential.Password = "123";
                         DateTime dtThoiDiemKhoaSoGanNhat = client.GetThoiDiemKhoaSoGanNhatOut(drChonCSDL.Text, DateTime.Now);
                         //ThoiDiemKhoaSo thoiDiemKhoaSoGanNhat = new ThoiDiemKhoaSo(dtThoiDiemKhoaSoGanNhat.Rows[0]);
                         client.Close();
                         ngayBatDau = dtThoiDiemKhoaSoGanNhat;
                     }
                     catch (Exception ex)
                     {
                         Error.Text = (ex.ToString());
                     }
                     ngayKetThuc = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 23, 59, 59);
                     break;
                 case "Cả năm":
                     txtThoigian1.Enabled = false;
                     txtThoigian2.Enabled = false;
                     ngayBatDau = new DateTime(DateTime.Now.Year, 1, 1);
                     ngayKetThuc = new DateTime(DateTime.Now.Year, 12, 31, 23, 59, 59);
                     break;
                 case "Quý I":
                     txtThoigian1.Enabled = false;
                     txtThoigian2.Enabled = false;
                     ngayBatDau = new DateTime(DateTime.Now.Year, 1, 1);
                     ngayKetThuc = new DateTime(DateTime.Now.Year, 3, 31, 23, 59, 59);
                     break;
                 case "Quý II":
                     txtThoigian1.Enabled = false;
                     txtThoigian2.Enabled = false;
                     ngayBatDau = new DateTime(DateTime.Now.Year, 4, 1);
                     ngayKetThuc = new DateTime(DateTime.Now.Year, 6, 30, 23, 59, 59);
                     break;
                 case "Quý III":
                     txtThoigian1.Enabled = false;
                     txtThoigian2.Enabled = false;
                     ngayBatDau = new DateTime(DateTime.Now.Year, 7, 1);
                     ngayKetThuc = new DateTime(DateTime.Now.Year, 9, 30, 23, 59, 59);
                     break;
                 case "Quý IV":
                     txtThoigian1.Enabled = false;
                     txtThoigian2.Enabled = false;
                     ngayBatDau = new DateTime(DateTime.Now.Year, 10, 1);
                     ngayKetThuc = new DateTime(DateTime.Now.Year, 12, 31, 23, 59, 59);
                     break;
                 default:
                     try
                     {
                         txtThoigian1.Enabled = false;
                         txtThoigian2.Enabled = false;
                         string strThang = ((string)drKyBaoCao.SelectedItem.Text).Substring(((string)(drKyBaoCao.SelectedItem.Text)).LastIndexOf(" "));
                         int thang = int.Parse(strThang);

                         ngayBatDau = new DateTime(DateTime.Now.Year, thang, 1);
                         ngayKetThuc = new DateTime(DateTime.Now.Year, thang,
                                         DateTime.DaysInMonth(DateTime.Now.Year, thang), 23, 59, 59);
                     }
                     catch (Exception ex)
                     {
                         throw new Exception(ex.Message);
                     }
                     break;
             }
             client.Close();
             txtThoigian1.Text = ngayBatDau.ToString("dd/MM/yyyy");
             txtThoigian2.Text = ngayKetThuc.ToString("dd/MM/yyyy");
           

         }

         public static string Decimal2Money(decimal money)
         {
             try
             {
                 string ret = "";
                 bool soAm = false;
                 if (money < 0)
                 {
                     money = -money;
                     soAm = true;
                 }

                 double real = Math.Floor((double)money);
                 while (real >= 1000)
                 {
                     string tem = ((int)(real % 1000)).ToString();
                     if (tem.Length == 1) tem = "00" + tem;
                     else if (tem.Length == 2) tem = "0" + tem;
                     ret = tem + "." + ret;
                     real = Math.Floor(real / 1000);
                 }
                 ret = ((int)(real % 1000)).ToString() + "." + ret;
                 if (ret.EndsWith(".")) ret = ret.Substring(0, ret.Length - 1);
                 if (soAm) ret = "-" + ret;
                 return ret;
             }

             catch (Exception ex)
             {

             }
             return "";
         }

         protected void baocao_Click(object sender, System.EventArgs e)
         {
             ServiceReference1.BIPortalClient client = new ServiceReference1.BIPortalClient();

             //  ServiceReference1.BIPortalClient client = new BIPortalClient();
             string _DBName = "HuyHoangCenter";
             DateTime tungay = DateTime.Now;
             DateTime denngay = DateTime.Now;
             try
             {
                 tungay = DateTime.Parse(convertdate(txtThoigian1.Text));
             }
             catch
             {
                 tungay = DateTime.Now.AddDays(-1);
             }
             try
             {
                 denngay = DateTime.Parse(convertdate(txtThoigian2.Text));
             }
             catch
             {
                 denngay = DateTime.Now;
             }
               try
               {
                   client.ClientCredentials.Windows.ClientCredential.UserName = "other";
                   client.ClientCredentials.Windows.ClientCredential.Password = "123";
                   DateTime now = DateTime.Now;
                   bool congno = false;
                   if(tinhcongno.Checked)
                   {
                       congno = true;
                   }
                   string xml = client.ThongTinTongTheOut(_DBName, tungay, denngay, congno);
              //decimal[] result = client.KPITyLeLoiNhuanOut(_DBName, now.AddDays(-1), now);
                   Stream stream = StringToStream(xml);
                   //Phải đọc qua dataset, qua table trực tiếp k được
                   DataSet ds = new DataSet();
                   ds.ReadXml(stream);
                   DataTable dt = ds.Tables[0];

                   foreach (DataRow row in dt.Rows)
                   {
                       string key = "";
                       string values = "";
                       decimal value = (decimal)0;
                       if (row != null)
                       {
                           if (row["Key"] is string)
                               key = row["Key"].ToString();
                           if (row["Value"] is string)
                               try
                               {

                                   values = (string)(row["Value"]);
                               //    values = values.Replace(".", ",");
                                   value = Convert.ToDecimal(values);
                                   //  Response.Write("<br/>" + value);
                               }
                               catch (Exception) { }
                       }

                       switch (key)
                       {
                           case "TM":
                               ucDigitalNumberTienMat.Text = String.Format("{0:### ### ### ###}", value);

                               break;
                           case "TGNH":
                               ucDigitalNumberTienGuiNganHang.Text = String.Format("{0:### ### ### ###}", value);
                               break;
                           case "GVHH":
                               ucDigitalNumberHangHoa.Text = String.Format("{0:### ### ### ###}", value);
                               break;
                           case "CNPThu":
                               ucDigitalNumberPhaiThu.Text = String.Format("{0:### ### ### ###}", value);
                               break;
                           case "CNPTra":
                               ucDigitalNumberPhaiTra.Text = String.Format("{0:### ### ### ###}", value);
                               break;
                           case "TT":
                               ucDigitalNumberTongThu.Text = String.Format("{0:### ### ### ###}", value);
                               break;
                           case "TC":
                               ucDigitalNumberTongChi.Text = String.Format("{0:### ### ### ###}", value);
                               break;
                           case "TNV":
                               ucDigitalNumberThuNguonVon.Text = String.Format("{0:### ### ### ###}", value);
                               break;
                           case "TK":
                               ucDigitalNumberThuKhac.Text = String.Format("{0:### ### ### ###}", value);
                               break;
                           case "TBH":
                               ucDigitalNumberThuBanHang.Text = String.Format("{0:### ### ### ###}", value);
                               break;
                           case "CK":
                               ucDigitalNumberChiKhac.Text = String.Format("{0:### ### ### ###}", value);
                               break;
                           case "CPHD":
                               ucDigitalNumberTongChiPhiHoatDong.Text = String.Format("{0:### ### ### ###}", value);
                               break;
                           case "CPSX":
                               ucDigitalNumberChiPhiSanXuat.Text = String.Format("{0:### ### ### ###}", value);
                               break;
                           case "CTNV":
                               ucDigitalNumberChiNguonVon411.Text = String.Format("{0:### ### ### ###}", value);
                               break;
                           case "CMH":
                               ucDigitalNumberChiMuaHang.Text = String.Format("{0:### ### ### ###}", value);
                               break;
                           case "LG":
                               ucDigitalNumberLaiGop.Text = String.Format("{0:### ### ### ###}", value);
                               break;
                           case "DSBB":
                               ucDigitalNumberDoanhSoBanBuon.Text = String.Format("{0:### ### ### ###}", value);
                               break;
                           case "DSBL":
                               ucDigitalNumberDoanhSoBanLe.Text = String.Format("{0:### ### ### ###}", value);
                               break;
                           //
                           case "DSSBBuon":
                               ucDoanhSoBanBuonSach.Text = String.Format("{0:### ### ### ###}", value);
                               break;
                           case "DSSBLe":
                               ucDoanhSoBanLeSach.Text = String.Format("{0:### ### ### ###}", value);
                               break;
                           case "DSVPPBBuon":
                               ucDoanhSoBanBuonHangKhac.Text = String.Format("{0:### ### ### ###}", value);
                               break;
                           case "DSVPPLe":
                               ucDoanhSoBanLeHangKhac.Text = String.Format("{0:### ### ### ###}", value);
                               break;
                           case "LaiBB":
                               ucDigitalNumberLaiGopBanBuon.Text = String.Format("{0:### ### ### ###}", value);
                               break;
                           case "LaiBL":
                               ucDigitalNumberLaiGopBanLe.Text = String.Format("{0:### ### ### ###}", value);
                               break;
                           //
                           case "LTCP":
                               ucDigitalNumberLaiTruChiPhi.Text = String.Format("{0:### ### ### ###}", value);
                               break;
                           case "TTNGTGT":
                               ucDigitalNumberThueThuNhap.Text = String.Format("{0:### ### ### ###}", value);
                               break;
                           case "LR":
                               ucDigitalNumberLoiNhuanThuc.Text = String.Format("{0:### ### ### ###}", value);
                               break;
                           case "NVKD":
                               ucDigitalNumberNguonVon.Text = String.Format("{0:### ### ### ###}", value);
                               break;
                           default:
                               break;
                       }
                   }
                   // dtStart = new System.DateTime(2014, 5, 1);

                   client.Close();
               }
               catch (Exception ex)
               {
                   Response.Write(ex.Message);
               }
               finally
               {
                   client.Close();
               }
         }
         public string convertdate(string date)
         {
             string res = "";
             string[] d = date.Split('/');
             if (d.Length > 2)
             {
                 res = d[1] + "/" + d[0] + "/" + d[2];
             }
             return res;

         }

        //2016-04-11T08:09:41.327+07:00
         public string convertTime(string date)
         {
             string res = "";
             try
             {
                 string[] d = date.Split('T');
                 if (d.Length > 1)
                 {
                     string[] d2 = d[1].Split('.');
                     res = d[0] + " " + d2[0];
                 }
             }
             catch
             {

             }
             
             return res;

         }
        public List<DonViHanhChinhInfo> Addgiatri(List<DonViHanhChinhInfo> ds,DonViHanhChinhInfo objTD )
        {
            bool checck = false;
            string dt = "";
            List<DonViHanhChinhInfo> listds = new List<DonViHanhChinhInfo>();
                //ds;
            if(ds==null || ds.Count ==0)
            {
                listds.Add(objTD);
                dt += ("Addgiaitri khoi tao Code: " + objTD.code + ". value  " + objTD.temp_double1 + "<br/>");
                return listds;
            }

            for (int i = 0; i < ds.Count; i++)
            {
                listds.Add(ds[i]);
            }
            for (int i = 0; i < listds.Count; i++ )
            {
                if (listds[i].code == objTD.code)
                {
                    
                    listds[i].temp_double1 += objTD.temp_double1;
                    dt += ("Addgiaitri Cộng Code: " + objTD.code + ". ");
                    dt += (" value : " + objTD.temp_double1 + " Tong " + listds[i].temp_double1 + "<br/>");
                    checck = true;
                }
            }
            //trường hợp không có mã
            if(!checck)
            {
                listds.Add(objTD);
                dt += ("Addgiaitri new Code: " + objTD.code + ". value  " + objTD.temp_double1 + "<br/>");

            }
           // chart.Text += (dt);
            return listds;
        }
        public List<DonViHanhChinhInfo> Addgiatri(List<DonViHanhChinhInfo> ds, DonViHanhChinhInfo objTD, int option)
        {
            bool checck = false;
            string dt = "";
            List<DonViHanhChinhInfo> listds = new List<DonViHanhChinhInfo>();
            //ds;
            if (ds == null || ds.Count == 0)
            {
                listds.Add(objTD);
                dt += ("Addgiaitri khoi tao Code: " + objTD.code + ". value  " + objTD.temp_double1 + "<br/>");
                return listds;
            }

            for (int i = 0; i < ds.Count; i++)
            {
                listds.Add(ds[i]);
            }
            if (option == 1)
            {
                for (int i = 0; i < listds.Count; i++)
                {
                    if (listds[i].title == objTD.title)
                    {
                        listds[i].temp_double1 += objTD.temp_double1;
                        checck = true;
                    }
                }
            }
            if (option == 2)
            {
                for (int i = 0; i < listds.Count; i++)
                {
                    if (listds[i].temp_string2 == objTD.temp_string2)
                    {
                        listds[i].temp_double1 += objTD.temp_double1;
                        checck = true;
                    }
                }
            }
            if (option == 3)
            {
                for (int i = 0; i < listds.Count; i++)
                {
                    if (listds[i].temp_string3 == objTD.temp_string3)
                    {
                        listds[i].temp_double1 += objTD.temp_double1;
                        checck = true;
                    }
                }
            }
            //trường hợp không có mã
            if (!checck)
            {
                listds.Add(objTD);
                

            }
            // chart.Text += (dt);
            return listds;
        }
        public string getCode(List<DonViHanhChinhInfo> ds,DonViHanhChinhInfo objTD)
        {
            for(int i=0; i<ds.Count; i++)
            {
                if(ds[i].code == objTD.code)
                {
                    return objTD.code + " (Số phát sinh = <font color = 'red'><b>" + String.Format("{0:### ### ### ###}", ds[i].temp_double1) + "</b></font>)";
                }
            }
            return objTD.code;
        }
        public string getCode(List<DonViHanhChinhInfo> ds, DonViHanhChinhInfo objTD, int option)
        {
            if (option == 1)
            {
                for (int i = 0; i < ds.Count; i++)
                {
                    if (ds[i].title == objTD.title)
                    {
                        return objTD.title + " (Số phát sinh = <font color = 'red'><b>" + String.Format("{0:### ### ### ###}", ds[i].temp_double1) + "</b></font>)";
                    }
                }
            }
            if (option == 2)
            {
                for (int i = 0; i < ds.Count; i++)
                {
                    if (ds[i].temp_string2 == objTD.temp_string2)
                    {
                        return objTD.temp_string2 + " (Số phát sinh = <font color = 'red'><b>" + String.Format("{0:### ### ### ###}", ds[i].temp_double1) + "</b></font>)";
                    }
                }
            }
            if (option == 3)
            {
                for (int i = 0; i < ds.Count; i++)
                {
                    if (ds[i].temp_string3 == objTD.temp_string3)
                    {
                        return objTD.temp_string3 + " (Số phát sinh = <font color = 'red'><b>" + String.Format("{0:### ### ### ###}", ds[i].temp_double1) + "</b></font>)";
                    }
                }
            }
            return objTD.code;
        }
}
}

